<?php

namespace api\app\controller;

use api\app\model\AdminModel;
use api\app\model\DeliveryModel;
use api\app\model\SmsCodeModel;
use api\app\validate\AdminValidate;
use api\app\validate\DeliveryValidate;
use cmf\controller\RestBaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Db;
use think\Filesystem;
use think\Request;

class AdminController extends RestBaseController
{
    //注册
    public function register(Request $request)
    {
        $data = $request->param();
        $validate = new AdminValidate();
        $val = $validate->scene('register')->check($data);
        if (!$val) {
            $this->error($validate->getError());
        }

        //验证验证码
        CheckSmsCode($data['mobile'], $data['code']);
        //入库
        $res = AdminModel::create($data);
        if($res)
        {
            $this->success('注册成功');
        }else{
            $this->error('注册失败');
        }
    }

    //登录api
    public function login(Request $request)
    {
        $mobile = $request->param('mobile');
        $code = $request->param('code');

        if(empty($mobile))
        {
            $this->error('手机号码不能为空');
        }
        if(empty($code)){
            $this->error('验证码不能为空');
        }
        $res = AdminModel::where('mobile','=',$mobile)
            ->find();
        if(empty($res))
        {
            $this->error('手机号错误');
        }
        $sms = SmsCodeModel::where('mobile','=',$mobile)
            ->find();
        if(CheckSmsCode($mobile, $sms['code']))
        {
            $token = sendToken($res['id'],$mobile);
            $this->success(
                '登录成功',
                [
                    'data'=>$token
                ]
            );
        }else{
            $this->error('登录失败');
        }
    }
    public function SentCode(Request $request)
    {
        $mobile = $request->param('mobile');
        //发送验证码
        sendAliSms($mobile);
    }

    //修改用户信息
    public function select()
    {
        $list = Db::name('register')
            ->select();
        $this->success('用户信息',$list);
    }

    //本地上传头像
    public function userimage(Request $request)
    {
        $image = $request->file('image');
        $image = Filesystem::disk('public')->putFile('image', $image);
        halt($image);
    }

    //七牛云上传
    public function qiniuyun()
    {
        $file = request()->file('file');
        if (!$file) {
            halt('file error');
        }
        $accessKey =Config("app.qiniuOss.accessKey");
        $secretKey = Config("app.qiniuOss.secretKey");
        $bucket = Config("app.qiniuOss.bucket");
        //构建鉴权对象
        $auth = new Auth($accessKey,$secretKey);
        //生成上传token
        $token = $auth->uploadToken($bucket);
        //本地地址："C:\Users\联想\Desktop\帅.jpg"
        $filePath = $file->getPathname();
        //上传到储存后保存的文件名
        $key = time(). '.' . $file->getOriginalExtension();
        //初始化UploadManager对象并进行文件上传
        $uploadMar = new UploadManager();
        list($return, $error) = $uploadMar->putFile($token, $key, $filePath);
        if ($error !== null) {
            $this->error('upload error');
        }else{
            $this->success('upload success', [
                'url' => 'sejrxikb1.hb-bkt.clouddn.com' . $return['key']
            ]);
        }
    }

    //修改用户信息
    public function userupdate(Request $request)
    {
        $mobile = $request->param('mobile');
        $username = $request->param('username');
        $userimage = $request->param('userimage');
        $res = AdminModel::where('mobile','=',$mobile)
            ->update([
                'username' => $username,
                'userimage' => $userimage
            ]);
        if (!empty($res)) {
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }

    //查找收货地址
    public function delivery(Request $request)
    {
        $token = $request->header();
        if(!isset($token['token']) || empty($token['token']))
        {
            $this->error('缺少token');
        }
        $key = new Key(config('app.jwt_key'),'HS256');

        try {
            $res = JWT::decode($token['token'],$key);
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $page = input('page/d',1);
        $pageSize = input('page_size/d',10);
        $list = DeliveryModel::field('mobile,username,address1,address2')
            ->order('id','desc')
            ->where('mobile','=',$res->data->mobile)
            ->page($page,$pageSize)
            ->select();

        $this->success('收货信息列表',$list);
    }

    //添加收货地址
    public function adddelivery()
    {
        $data = input();
        //验证数据
        $validate = new DeliveryValidate();
        $result = $validate->scene('add')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $data['create_time'] = date('Y:m:d H:i:s');
        $add = DeliveryModel::create($data);
        if($add){
            $this->success('添加成功');
        }
        $this->error('添加失败');
    }

    //修改收货地址
    public function updatedelivery()
    {
        $data = input();
        //验证数据
        $validate = new DeliveryValidate();
        $result = $validate->scene('edit')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $data['update_time'] = date('Y:m:d H:i:s');
        $edit = DeliveryModel::where('id','=',$data['id'])
            ->update($data);
        if($edit){
            $this->success('修改成功');
        }
        $this->error('修改失败');
    }

}